package spark.network.protocol;

import spark.network.Util;

public abstract class Response<RequestType extends Base> extends Base{
	private Class<RequestType> requestTypeClass;
	private RequestType request;
	/**
	 * PacketId of the packet this is a response to
	 */
	private long responseToId;
	public static final int RESPONSE_OFFSET = Base.SIZE;
	public static final int RESPONSE_LENGTH = Long.SIZE / 8;

	protected static final int SIZE =
			Base.SIZE +
	        RESPONSE_LENGTH;

	protected Response(boolean isReliable, byte[] typeBytes, Class<RequestType> requestTypeClass) {
		super(isReliable, typeBytes);
		this.requestTypeClass = requestTypeClass;
	}

	protected Response(boolean isReliable, byte[] typeBytes, RequestType request, Class<RequestType> requestTypeClass) {
		this(isReliable, typeBytes, requestTypeClass);
		setResponseToId(request.getPacketId());
	}

	public long getResponseToId() {
		return responseToId;
	}

	public void setResponseToId(long responseToId) {
		this.responseToId = responseToId;
	}

	public RequestType getRequest() {
		return request;
	}

	public void setRequest(RequestType request) {
		this.request = request;
	}

	public Class<RequestType> getRequestTypeClass() {
		return requestTypeClass;
	}

	@Override
	public void getBytes(byte[] buffer) {
		super.getBytes(buffer);
		Util.arraycopy(Util.makeBytes(responseToId), 0, buffer, RESPONSE_OFFSET);
	}

	@Override
	public void fill(byte[] buffer) {
		super.fill(buffer);
		responseToId = Util.makeLong(buffer, RESPONSE_OFFSET);
	}

	@Override
	public int getSize() {
		return SIZE;
	}
}
